package com.qsign.sfrz_android.activity.home.ViewController;

import android.app.Dialog;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.example.print_sdk.PrintUtil;
import com.google.gson.Gson;
import com.qsign.sfrz_android.R;
import com.qsign.sfrz_android.activity.home.Model.FuheModel;
import com.qsign.sfrz_android.activity.home.Model.PrintContract;
import com.qsign.sfrz_android.base.NewBaseActivity;
import com.qsign.sfrz_android.net.IServiceImpl;
import com.qsign.sfrz_android.net.RequestServiceImpl;
import com.qsign.sfrz_android.publicview.SimpleDialog;
import com.qsign.sfrz_android.utils.BaseUtil;
import com.zhy.autolayout.utils.AutoUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class FuheHistoryActivity extends NewBaseActivity {
    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;

    QuickAdapter quickAdapter;
    List<FuheModel> fuheArray = new ArrayList<FuheModel>();
    PrintContract printContract;
    int pagenumber = 0;
    int number = 1000000001; // 初始化票据流水号 Initial bill serial number
    FuheModel fuheModel;
    @BindView(R.id.nextbtn)
    Button nextbtn;
    TextView  rightext;
    FuheModel thismodel;
    @Override
    protected void initTitle(TextView textView) {
        textView.setText("已打印列表");
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_fuhehistory;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        fuheModel = (FuheModel) getIntent().getExtras().getSerializable("FuheModel");
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerview.setLayoutManager(layoutManager);
        //给RecyclerView设置适配器
        quickAdapter = new QuickAdapter();
        recyclerview.setAdapter(quickAdapter);
        if(!getIntent().getBooleanExtra("printshow",false)){//不显示
            nextbtn.setVisibility(View.GONE);
        }else{
            nextbtn.setVisibility(View.VISIBLE);
        }
        rightext=(TextView)this.findViewById(R.id.rightext);
        rightext.setVisibility(View.VISIBLE);

        PrintUtil pUtil = PrintUtil.getClient();
        pUtil.setPrintEventListener(new PrintUtil.OnPrintEventListener() {
            @Override
            public void onPrintStatus(int state) {
                Log.e(TAG, "onPrintState: " + state);
                switch (state) {
                    case 0:
                        number += 1; // 流水号自加1 Serial number plus 1
                        pagenumber--;

                        Toast.makeText(FuheHistoryActivity.this, "打印成功", Toast.LENGTH_SHORT).show();
                        break;
                    case 1:
                        Toast.makeText(FuheHistoryActivity.this, "没有打印纸了", Toast.LENGTH_SHORT).show();
                        break;
                    case 2:
                        Toast.makeText(FuheHistoryActivity.this, "打印失败", Toast.LENGTH_SHORT).show();
                        break;

                }
            }

            @Override
            public void onVersion(String version) {
                Log.e(TAG, "onVersion: " + version);
            }
        });

        printContract = new PrintContract(this, pUtil);
        printContract.printInit();

        showWait();
        RequestServiceImpl.fh_itemclick(mMIPHandler, IServiceImpl.FUHEITEMCLICK,fuheModel.getPKID());
    }


    public class QuickAdapter extends BaseQuickAdapter<FuheModel, BaseViewHolder> {
        public QuickAdapter() {
            super(R.layout.fuhe_history_item, fuheArray);
        }

        @Override
        protected BaseViewHolder createBaseViewHolder(View view) {
            AutoUtils.auto(view);
            return super.createBaseViewHolder(view);
        }

        @Override
        protected void convert(BaseViewHolder holder, final FuheModel item) {
            TextView indext = holder.getView(R.id.numberno);
            TextView SZXX = holder.getView(R.id.SZXX);
            TextView DIRECTION = holder.getView(R.id.DIRECTION);
            TextView YARNTYPE = holder.getView(R.id.YARNTYPE);
            TextView ORIPLACE = holder.getView(R.id.ORIPLACE);
            TextView BATCHNO = holder.getView(R.id.BATCHNO);
            TextView TPZL = holder.getView(R.id.TPZL);
            TextView TRAYCODE = holder.getView(R.id.TRAYCODE);
            Button itemdeletebtn=holder.getView(R.id.itemdeletebtn);
            RelativeLayout itemlay= holder.getView(R.id.itemlay);

            indext.setText(holder.getLayoutPosition() + 1 + "");
            SZXX.setText(item.getSZXX());
            DIRECTION.setText(item.getDIRECTION());
            YARNTYPE.setText(item.getYARNTYPE());
            ORIPLACE.setText(item.getORIPLACE());
            BATCHNO.setText(item.getBATCHNO());
            TPZL.setText(item.getTPZL());
            TRAYCODE.setText(item.getTRAYCODE());

            if(item.getSTATE().equals("已入库")||!getIntent().getBooleanExtra("printshow",false)){
                itemdeletebtn.setVisibility(View.GONE);
            }else{
                itemdeletebtn.setVisibility(View.VISIBLE);
            }

            if(item.getSTATE().equals("已打印")){
                itemlay.setBackgroundColor(Color.rgb(	255,228,181));
            }else{
                itemlay.setBackgroundColor(Color.rgb(	255,255,255));
            }

            holder.getView(R.id.itemprintbtn).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {//打印弹出框
                    View viewTips = LayoutInflater.from(FuheHistoryActivity.this).inflate(R.layout.print_num_dialog, null);
                    AutoUtils.auto(viewTips);
                    Dialog alertDialog = BaseUtil.ShowMYDialog(FuheHistoryActivity.this, viewTips, 340);
                    alertDialog.show();
                    EditText numberedit = viewTips.findViewById(R.id.numberedit);

                    viewTips.findViewById(R.id.printbtn).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            alertDialog.dismiss();
                            closeKeyboard();
                            if (numberedit.getEditableText().toString().length() == 0) {
                                BaseUtil.ShowToast(FuheHistoryActivity.this, "请输入打印数量");
                            } else {
                                pagenumber = Integer.parseInt(numberedit.getEditableText().toString());
                                thismodel=item;
                                if(thismodel.getSTATE().equals("已入库")||!getIntent().getBooleanExtra("printshow",false)){
                                    showWait();
                                    RequestServiceImpl.printitem(mMIPHandler, IServiceImpl.PRINTITEM,thismodel.getTRAYCODE());
                                }else{
                                    new Thread(new Runnable() {
                                        @Override
                                        public void run() {
                                            for (int i = 0; i < pagenumber; i++) {
                                                printContract.printBarcode(thismodel.getTRAYCODE(), number);
                                            }
                                        }
                                    }).start();
                                }

                            }

                        }
                    });
                    viewTips.findViewById(R.id.cancellay).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            alertDialog.dismiss();
                            closeKeyboard();
                        }
                    });
                    numberedit.setOnFocusChangeListener(new View.
                            OnFocusChangeListener() {
                        @Override
                        public void onFocusChange(View v, boolean hasFocus) {
                            if (hasFocus) {
                                showKeyboard(numberedit);
                            } else {
                                closeKeyboard();
                            }
                        }
                    });
                }
            });

            holder.getView(R.id.itemdeletebtn).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showWait();
                    RequestServiceImpl.pihaodelete(mMIPHandler, IServiceImpl.PIHAODELETE, item.getPKID());
                }
            });
        }
    }

    @Override
    public void onPostHandle(int requestType, Object objBody, boolean error) throws Exception {
        stopWait();
        String msg = "";
        String opt = "";
        switch (requestType) {
            case IServiceImpl.FUHEITEMCLICK://
                try {
                    JSONObject jsonObject = JSONObject.parseObject(objBody.toString());
                    msg = jsonObject.getString("MSG_INFO");
                    opt = jsonObject.getString("OPT_FLAG");
                    if ("SUCCESS".equals(opt)) {
                        JSONArray dataarray = jsonObject.getJSONArray("DATA");
                        rightext.setText("剩余："+jsonObject.getString("SYZL"));
                        fuheArray.clear();
                        if (dataarray != null && dataarray.size() > 0) {
                            Gson gson = new Gson();
                            for (Object o : dataarray) {
                                JSONObject jsonObject1 = (JSONObject) o;
                                FuheModel qrBean = gson.fromJson(jsonObject1.toJSONString(), FuheModel.class);
                                fuheArray.add(qrBean);
                            }
                        }

                        float mm=(float)(Double.parseDouble(fuheModel.getYLZL())-Double.parseDouble(jsonObject.getString("SYZL")));
                        fuheModel.setYDYZL(mm+"");

                        quickAdapter.notifyDataSetChanged();
                        quickAdapter.setEmptyView(R.layout.empty, (ViewGroup) recyclerview.getParent());
                    } else {
                        if (TextUtils.isEmpty(msg)) {
                            showSimpleDialog("查询出错");
                        } else {
                            showSimpleDialog(msg);
                        }

                    }
                } catch (Exception e) {
                }
                break;
            case IServiceImpl.PIHAODELETE://
                try {
                    JSONObject jsonObject = JSONObject.parseObject(objBody.toString());
                    msg = jsonObject.getString("MSG_INFO");
                    opt = jsonObject.getString("OPT_FLAG");
                    if ("SUCCESS".equals(opt)) {
                        showWait();
                        RequestServiceImpl.fh_itemclick(mMIPHandler, IServiceImpl.FUHEITEMCLICK,fuheModel.getPKID());
                    } else {
                        if (TextUtils.isEmpty(msg)) {
                            showSimpleDialog("打印出错");
                        } else {
                            showSimpleDialog(msg);
                        }

                    }

                } catch (Exception e) {
                }
                break;

            case IServiceImpl.PRINTNO://
                try {
                    JSONObject jsonObject = JSONObject.parseObject(objBody.toString());
                    msg = jsonObject.getString("MSG_INFO");
                    opt = jsonObject.getString("OPT_FLAG");
                    if ("SUCCESS".equals(opt)) {
                        String TRAYCODE= jsonObject.getString("TRAYCODE");
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                for(int i=0;i<pagenumber;i++){
                                    printContract.printBarcode (TRAYCODE,number);
                                }
                            }
                        }).start();

                        showWait();
                        RequestServiceImpl.fh_itemclick(mMIPHandler, IServiceImpl.FUHEITEMCLICK,fuheModel.getPKID());

                    } else {
                        if (TextUtils.isEmpty(msg)) {
                            showSimpleDialog("打印出错");
                        } else {
                            showSimpleDialog(msg);
                        }

                    }

                } catch (Exception e) {
                }
                break;
            case IServiceImpl.PRINTITEM://
                try {
                    JSONObject jsonObject = JSONObject.parseObject(objBody.toString());
                    msg = jsonObject.getString("MSG_INFO");
                    opt = jsonObject.getString("OPT_FLAG");
                    if ("SUCCESS".equals(opt)) {
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                for (int i = 0; i < pagenumber; i++) {
                                    printContract.printBarcode(thismodel.getTRAYCODE(), number);
                                }
                            }
                        }).start();
                        showWait();
                        RequestServiceImpl.fh_itemclick(mMIPHandler, IServiceImpl.FUHEITEMCLICK,fuheModel.getPKID());
                    } else {
                        if (TextUtils.isEmpty(msg)) {
                            showSimpleDialog("打印出错");
                        } else {
                            showSimpleDialog(msg);
                        }

                    }

                } catch (Exception e) {
                }
                break;
        }
    }

    @OnClick({R.id.backbtn, R.id.nextbtn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.backbtn:
                finish();
                break;
            case R.id.nextbtn:
                View viewTips = LayoutInflater.from(this).inflate(R.layout.print_dialog, null);
                AutoUtils.auto(viewTips);
                Dialog alertDialog = BaseUtil.ShowMYDialog(this, viewTips, 340);
                alertDialog.show();
                TextView yuanliaotext = viewTips.findViewById(R.id.yuanliaotext);
                TextView changditext = viewTips.findViewById(R.id.changditext);
                TextView pihaotext = viewTips.findViewById(R.id.pihaotext);
                TextView ylzltext = viewTips.findViewById(R.id.ylzltext);
                TextView haveprinttext = viewTips.findViewById(R.id.haveprinttext);
                EditText numberedit = viewTips.findViewById(R.id.numberedit);
                EditText tuopanedit = viewTips.findViewById(R.id.tuopanedit);
                yuanliaotext.setText(fuheModel.getSZXX());
                changditext.setText(fuheModel.getORIPLACE());
                pihaotext.setText(fuheModel.getBATCHNO());
                ylzltext.setText(fuheModel.getYLZL());
                haveprinttext.setText(TextUtils.isEmpty(fuheModel.getYDYZL())?"":fuheModel.getYDYZL());

                viewTips.findViewById(R.id.printbtn).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        alertDialog.dismiss();
                        closeKeyboard();
                        if(tuopanedit.getEditableText().toString().length()==0){
                            BaseUtil.ShowToast(FuheHistoryActivity.this,"请输入托盘重量");
                        }else if(numberedit.getEditableText().toString().length()==0){
                            BaseUtil.ShowToast(FuheHistoryActivity.this,"请输入打印数量");
                        }else if(Double.valueOf(tuopanedit.getEditableText().toString())>Double.valueOf(fuheModel.getYLZL())){
                            BaseUtil.ShowToast(FuheHistoryActivity.this,"托盘重量不能大于总重量");
                        }else if(!TextUtils.isEmpty(fuheModel.getYDYZL())){
                            double mm=  Double.valueOf(fuheModel.getYLZL())- Double.valueOf(fuheModel.getYDYZL());
                            if(Double.valueOf(tuopanedit.getEditableText().toString())>mm){
                                BaseUtil.ShowToast(FuheHistoryActivity.this,"托盘重量不能大于剩余重量");
                            }else{
                                pagenumber=Integer.parseInt(numberedit.getEditableText().toString());
                                showWait();
                                RequestServiceImpl.print(mMIPHandler, IServiceImpl.PRINTNO,fuheModel.getPKID(),tuopanedit.getEditableText().toString());
                            }
                        } else{
                            pagenumber=Integer.parseInt(numberedit.getEditableText().toString());
                            showWait();
                            RequestServiceImpl.print(mMIPHandler, IServiceImpl.PRINTNO,fuheModel.getPKID(),tuopanedit.getEditableText().toString());
                        }

                    }

                });
                viewTips.findViewById(R.id.cancellay).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        alertDialog.dismiss();
                        closeKeyboard();
                    }
                });
                numberedit.setOnFocusChangeListener(new View.
                        OnFocusChangeListener() {
                    @Override
                    public void onFocusChange(View v, boolean hasFocus) {
                        if (hasFocus) {
                            showKeyboard(numberedit);
                        } else {
                            closeKeyboard();
                        }
                    }
                });
                tuopanedit.setOnFocusChangeListener(new View.
                        OnFocusChangeListener() {
                    @Override
                    public void onFocusChange(View v, boolean hasFocus) {
                        if (hasFocus) {
                            showKeyboard(tuopanedit);
                        } else {
                            closeKeyboard();
                        }
                    }
                });
                tuopanedit.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {

                    }

                    @Override
                    public void afterTextChanged(Editable s) {
                        if (s == null) {
                            return;
                        }
                        String temp = s.toString();
                        int posDot = temp.indexOf(".");
                        int index = tuopanedit.getSelectionStart();
                        if (posDot >= 0 && temp.length() - 3 > posDot) {
                            s.delete(index - 1, index);
                        }
                    }
                });
                break;
        }
    }

    private void showSimpleDialog(String message) {
        SimpleDialog.show(this, message);
    }
}
